package com.example.movie.controller;

import com.example.movie.domain.Comment;
import com.example.movie.domain.R;
import com.example.movie.domain.User;
import com.example.movie.service.CommentService;
import com.example.movie.service.UserService;
import com.example.movie.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public R getComments(@RequestParam(value = "movieId") Integer movieId, @RequestParam(value = "currentPage")Long currentPage, @RequestParam(value = "pageSize")Long pageSize){
        if (currentPage <= 0 || pageSize <= 0) {
            return R.error("分页参数错误");
        }
        List<Comment> comments = commentService.getComments(movieId, currentPage, pageSize);
        List<Long> userIDS = comments.stream().map(Comment::getUserId).collect(Collectors.toList());
        List<User> userList = userService.getUserListByUserIDS(userIDS);
        Map<Long, String> userId2Name = userList.stream().collect(Collectors.toMap(User::getUId, User::getName));
        comments.forEach(item->{
            String userName = userId2Name.getOrDefault(item.getUserId(), "未知用户");
            item.setUserName(userName);
        });
        return R.ok(comments);
    }

    @PostMapping("/add")
    public R addComment(@RequestBody Comment comment, HttpServletRequest request){
        if(comment.getMovieId() == null){
            return R.error("评论错误");
        }
        comment.setUserId(UserUtil.getUserInfo(request).getUId());
        commentService.saveOrUpdate(comment);
        return R.ok("评论成功");
    }

    @DeleteMapping("/delete")
    public R deleteComment(@RequestParam(value = "commentId") Long commentId){
        commentService.removeById(commentId);
        return R.ok();
    }
}
